package com.dx.oa.sysmng.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dx.oa.framework.dto.TreeDto;
import com.dx.oa.framework.util.TreeUtil;
import com.dx.oa.framework.util.UserUtils;
import com.dx.oa.sysmng.entity.Dict;
import com.dx.oa.sysmng.entity.Menu;
import com.dx.oa.sysmng.entity.User;
import com.dx.oa.sysmng.service.IMenuService;

@Controller
@RequestMapping("/sysmgr/menu")
public class MenuController {
	
	@Autowired
	private IMenuService menuService;

	private static Logger logger = Logger.getLogger(MenuController.class);

	/**
	 * 进入字典查询功能
	 * @return
	 */
	@RequestMapping("/gotoMenuList")
	public String gotoMenuList(Model model)
	{
		
		List<Menu> sortMenuList = new ArrayList<Menu>();
		List<Menu> menuList =  menuService.getMenuListById(UserUtils.getCurrentUserId());
		TreeUtil.sortTreeList(menuList, sortMenuList, 0);
		model.addAttribute("menuList",sortMenuList);
		
		return "sysmanage/menu/menuList";
	}
	
	//进入字典编辑功能
	@RequestMapping("/gotoMenuEdit")
	public String gotoMenuEdit(@ModelAttribute("editFlag") int editFlag, Integer menuId,Integer parentId, Model model)
	{	
		if(editFlag == 2 && menuId != null)
		{
			model.addAttribute("menu", menuService.getMenuById(menuId));
		}
		if(editFlag == 1 && parentId != null)
		{
			Menu menu = new Menu();
			menu.setParentId(parentId);
			menu.setParentName(menuService.getMenuById(parentId).getName());
			model.addAttribute("menu", menu);
		}
		return "sysmanage/menu/menuEdit";
	}
	
	/**
	 * 对于树形结构的数据,我们在删除的时候需要注意,必须保证无子节点删除
	 * @param menuId
	 * @return
	 */

	@RequestMapping("/delMenu")
	public @ResponseBody Map<String,Object> delMenu(Integer menuId)
	{
		Map<String,Object> resultMap = new HashMap<String,Object>();
		if(menuService.getChildCnt(menuId) > 0)
		{
			resultMap.put("result", "请先删除该菜单下的子菜单");
			return resultMap;
		}
		try
		{
			int row = menuService.deleteMenuById(menuId);
			if(row > 0)
			{
				resultMap.put("result", "删除成功");
			}
			else
			{
				resultMap.put("result", "删除失败");
				logger.error("删除菜单失败");
			}
		}
		catch(Exception e)
		{
			resultMap.put("result", "删除失败");
			logger.error("删除菜单失败",e);
		}
		return resultMap;
	}

	/**
	 * 获取所有树形结构菜单节点信息，
	 * @param menuId
	 * @return
	 */
	@RequestMapping("/getParentMenuTreeData")
	public @ResponseBody List<TreeDto> getParentMenuTreeData(Integer menuId)
	{
		logger.info(menuId);
		//menuId = 30;

		List<TreeDto> resMenuList = new ArrayList<TreeDto>();
	
		List<Menu> menuList = menuService.getMenuList();
		
		for(Menu menu:menuList)
		{
			resMenuList.add(menu);
		}
		
		if(menuId != null)
		{
			Set<Integer> retSet = TreeUtil.getChildHashSet(resMenuList,menuId);
			List<TreeDto> retMenuList = new ArrayList<TreeDto>();
			for(TreeDto td:resMenuList)
			{
				if(!retSet.contains(td.getId()))
				{
					retMenuList.add(td);
				}
			}
			return retMenuList;
		}

		return resMenuList;
	}
	
	//保存修改
	@RequestMapping("/saveMenu")
	public @ResponseBody Map<String,String> saveMenu(Menu menu,HttpSession session,Model model)
	{
		Map<String,String> responseMap = new HashMap<String,String>();
		
		//System.out.println("mdict:"+ mdict.toString());
		
		if(menu == null)
		{
			responseMap.put("result", "操作失败");
			return responseMap;
		}
		menu.setDelFlag('0');
		menu.setUpdateBy(((User)session.getAttribute("user")).getUserNo());
		menu.setUpdateDate(new Timestamp(System.currentTimeMillis()));
		
		if(menu.getId() == null)
		{
			if(menuService.insertMenu(menu) > 0)
			{
				List<Menu> menuList =  menuService.getMenuList();
				List<Menu> sortMenuList = new ArrayList<Menu>();
				TreeUtil.sortTreeList(menuList, sortMenuList, 0);
				model.addAttribute("menuList", sortMenuList);
				responseMap.put("result", "插入成功");
			}
			else
				responseMap.put("result", "插入失败");
		}
		else
		{
			if(menuService.updateMenu(menu) > 0)
			{
				List<Menu> menuList =  menuService.getMenuList();
				List<Menu> sortMenuList = new ArrayList<Menu>();
				TreeUtil.sortTreeList(menuList, sortMenuList, 0);
				model.addAttribute("menuList", sortMenuList);
				responseMap.put("result","更新成功");
			}
			else
				responseMap.put("result", "更新失败");
		}
		return responseMap;
	}
	
	@RequestMapping("/toEdit")
	public String toEdit(Integer id)
	{
		if(id != null)
		{
			String href = menuService.getMenuById(id).getHref();
			if(href.indexOf("sysmgr") > 0 || href.indexOf("activitimgr") > 0)
				return "redirect:" + href;
			else
				return href;
		}
		return "#";
	}
	
	@RequestMapping("/gotoIconSelect")
	public String gotoIconSelect(@ModelAttribute("value") String value){		 
		return "sysmanage/menu/iconSelect";
	}
}
